﻿using TbShop.Business.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TbShop.Entity;
using TbShop.Web.Infrastructure;
using Newtonsoft.Json;
using TbShop.Web.Helpers;
using TbShop.Web.Areas.Admin.Models;

namespace TbShop.Web.Areas.Admin.Controllers
{
    public class AuthorityController : BaseController
    {
        private AuthorityBC authorityBC = new AuthorityBC();
        private RoleAuthorityBC roleAuthorityBC = new RoleAuthorityBC();
        /// <summary>
        /// 设置权限页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Setting()
        {
            var model = new AuthorityViewListModels();
            var authority = this.authorityBC.GetPagedList(1, 999999);
            model.AuthorityViewModels = DataMapperHelper.MapList<AuthorityViewModels>(authority.OrderBy(a => a.CreatedDate));
            model.Page = authority.GetMetaData();
            return View(model);
        }

        /// <summary>
        /// 更新单条权限状态
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <param name="authId">权限Id</param>
        /// <param name="checkedState">true-赋予权限 false-取消权限</param>
        [HttpPost]
        public void UpdateRoleAuthority(string roleId, int authId, bool checkedState)
        {
            if (!string.IsNullOrEmpty(roleId) && authId != 0)
            {
                if (checkedState)
                {
                    var ids = authorityBC.GetParentById(authId);
                    for (int i = 0; i < ids.Count(); i++)
                    {
                        if (ids[i] > 0)
                        {
                            var roleauthData = roleAuthorityBC.GetAuthorityByRoleAuth(roleId, ids[i]);
                            if (roleauthData == null)
                            {
                                RoleAuthority newItem = new RoleAuthority();
                                newItem.RoleId = roleId;
                                newItem.AuthorityId = ids[i];
                                newItem.FillEntity(OperationUser);
                                this.roleAuthorityBC.Save(newItem);
                            }
                        }
                    }
                }
                else
                {
                    var roleauthData = roleAuthorityBC.GetAuthorityByRoleAuth(roleId, authId);
                    if (roleauthData != null)
                    {
                        this.roleAuthorityBC.Remove(roleauthData);
                    }
                }
            }
        }

        /// <summary>
        /// 获取角色现有的权限
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <returns>角色现有权限的Id列表，JSON格式的字符串数组</returns>
        [HttpPost]
        public string GetRoleAuthority(string roleId)
        {
            int[] auth = new int[] { };
            auth = this.roleAuthorityBC.GetAuthoritysByRoleId(roleId);
            return JsonConvert.SerializeObject(auth);
        }

        /// <summary>
        /// 依据顶级权限Id，更新所有子权限状态
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <param name="authId">权限Id</param>
        /// <param name="checkedState">true-赋予权限 false-取消权限</param>
        [HttpPost]
        public void UpdateFatherRoleAuthority(string roleId, int authId, bool checkedState)
        {
            if (!string.IsNullOrEmpty(roleId) && authId != 0)
            {
                var auths = this.authorityBC.GetAuthoritysForRole(authId).ToList();
                if (auths.Any())
                {
                    foreach (var item in auths)
                    {
                        if (item != authId)
                        {
                            var secondList = authorityBC.GetAuthoritysForRole(item).ToList();
                            if (secondList.Any())
                            {
                                foreach (var sec in secondList)
                                {
                                    UpdateRoleAuthority(roleId, sec, checkedState);
                                }
                            }
                        }
                        UpdateRoleAuthority(roleId, item, checkedState);
                    }
                    OperationLogHelper.SaveOperationLog(AdminId, "修改", "角色", "权限", roleId.ToString());
                }
            }
        }

        public ActionResult AuthorityError()
        {
            return View();
        }
    }
}